package com.cloudsigns.factorymanager2;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

public abstract class BaseActivity extends Activity implements View.OnClickListener {
    /*日志输出标志*/
    protected final String TAG = this.getClass().getSimpleName();
    protected Dialog mDialog;
    public static final String DIALOG_RES = "DIALOG_RES";
    public static final int DIALOG_PROGRESS = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        if (!this.isTaskRoot()) { //判断该Activity是不是任务空间的源Activity，“非”也就是说是被系统重新实例化出来
            //如果你就放在launcher Activity中话，这里可以直接return了
            Intent mainIntent = getIntent();
            if (mainIntent != null) {
                String action = mainIntent.getAction();
                if (!TextUtils.isEmpty(action) && mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
                    finish();
                    return;//finish()之后该活动会继续执行后面的代码，你可以logCat验证，加return避免可能的exception
                }
            }
        }
        Log.v("BaseActivity", this.getClass().getName() + "=onCreate");
        onBaseCreate(savedInstanceState);
        super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initView(savedInstanceState);
        initData(savedInstanceState);
        setListener();
    }

    /**
     * 设置一个ContentView及其他的一些初始化
     *
     * @param savedInstanceState
     */
    protected abstract void onBaseCreate(Bundle savedInstanceState);

    /**
     * 视图初始化
     * <p>
     * 处理 view控件等初始化
     *
     * @param savedInstanceState
     */
    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void initData(Bundle savedInstanceState);

    /**
     * 设置监听
     */
    public abstract void setListener();

    /**
     * View点击
     *
     * @param view
     */
    public abstract void widgetClick(View view);

    @Override
    public void onClick(View v) {
        widgetClick(v);
    }

    /**
     * 简化Toast
     *
     * @param msg
     */
    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    /**
     * 隐藏软键盘
     */
    protected void hideSoftInputView() {
        InputMethodManager manager = ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE));
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 页面跳转
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(BaseActivity.this, clz));
    }

    /**
     * 携带数据的页面跳转
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 含有Bundle通过Class打开编辑界面
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart()");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart()");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume()");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy()");
    }

    @Override
    protected Dialog onCreateDialog(int id, Bundle args) {
        if (null == mDialog) {
            mDialog = new Dialog(this, R.style.Theme_LargeDialog);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            mDialog.setContentView(R.layout.dialog_loading_layout);
        }
        Object obj = args.get(DIALOG_RES);
        if (obj instanceof Integer) {
            ((TextView) mDialog.findViewById(R.id.textview_tips)).setText((Integer) obj);
        } else {
            ((TextView) mDialog.findViewById(R.id.textview_tips)).setText(obj.toString());
        }
        return mDialog;
    }

    /**
     * 显示进度对话框
     */
    public void showProgressDialog() {
        if (!this.isFinishing()) {
            Bundle data = new Bundle();
            data.putString(DIALOG_RES, "");
            showDialog(DIALOG_PROGRESS, data);
            timeShowProgressStart = System.currentTimeMillis();
            handlerProgress.postDelayed(runnableDismissProgresss, 15000);
        }
    }

    public final void showProgressDialog(int resId) {
        if (!this.isFinishing()) {
            Bundle data = new Bundle();
            data.putInt(DIALOG_RES, resId);
            showDialog(DIALOG_PROGRESS, data);
            timeShowProgressStart = System.currentTimeMillis();
            handlerProgress.postDelayed(runnableDismissProgresss, 40000);
        }
    }

    private long timeShowProgressStart;
    private Runnable runnableDismissProgresss = new Runnable() {
        @Override
        public void run() {
            if (System.currentTimeMillis() - timeShowProgressStart > 38000) {
                dismissAllDialog();
            }
        }
    };
    private Handler handlerProgress = new Handler();

    public void dismissAllDialog() {
        if (null != mDialog && mDialog.isShowing()) {
            mDialog.cancel();
            removeDialog(DIALOG_PROGRESS);
        }
        mDialog = null;
    }
}